package com.epcs.controller.action;

import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.epcs.model.bo.UserBO;
import com.epcs.model.dto.Account;
import com.epcs.util.DBUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AuthenticationAction extends ActionSupport implements SessionAware {

	// ---------- input fields ----------//
	private SessionMap<String, Object> sessionMap;
	private String username;
	private String password;
	private String errorMessage;

	// ----------Action method -----------//
	public String checkLogin() {
		String result = "Fail";
		UserBO bo = new UserBO();
		if(sessionMap.isEmpty()){
			System.out.println("sessionMap == null");
		}

		Account account = bo.checkLogin(username, password);
		if (account != null) {
			
			if (account.getIsActive()) {
				result = "Success";
				// tao session cho user
				
				sessionMap.put("USER_INFO", account);
				sessionMap.put("USER_ROLE", account.getRole().getRoleName());
			} else {
				errorMessage = "Tài khoản này đã bị khóa!";
			}
			
		} else {
			errorMessage = "Tên tài khoản, hoặc mật khẩu không hợp lệ!";
		}

		return result;
	}

	public String logout() {
		String result = "Success";
		
		if(!sessionMap.isEmpty()){
			sessionMap.invalidate();
			System.out.println("invalid session");
		}
		
		return result;
	}
	
	// -----------Getter and Setter -----//
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getErrorMessage() {
		return errorMessage;
	}
	
	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	// ---------------- session --------------------//
	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = (SessionMap<String, Object>) sessionMap;
//		System.out.println("session = " + sessionMap);
//		System.out.println("session map = " + sessionMap.toString());
//		System.out.println("session context = " + ActionContext.getContext().getSession().toString());
	}

}
